package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RegexPatterns;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 * 验证码发送：服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {


    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result sendCode(String phone, HttpSession session) {
        //校验手机号
        if(RegexUtils.isPhoneInvalid(phone)){
            //不符合，返回错误信息
            return Result.fail("手机号格式错误");
        }
        //符合，生成验证码
        String code = RandomUtil.randomNumbers(6);

        //保存验证码到seesion
        //session.setAttribute("code", code);

        //保存到seesion修改为将验证码保存至redis
        stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY+phone, code, LOGIN_CODE_TTL, TimeUnit.MINUTES);//加上业务前缀作为区分, 并设置验证码过期时间

        //发送验证码
        log.debug("已发送验证码 "+code);

        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        //1 校验手机号
        String phone = loginForm.getPhone();
        if(RegexUtils.isPhoneInvalid(phone)){
            //1.1 不符合，返回错误信息
            return Result.fail("手机号格式错误");
        }


        //2 校验验证码, 从redis中获取生成的验证码
        //String cacheCode = (String) session.getAttribute("code");
        String cacheCode = (String) stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY + phone);
        String code = loginForm.getCode();

        if(cacheCode==null || !cacheCode.toString().equals(code)){
            //2.1 不一致，报错
            return Result.fail("验证码错误");
        }

        //2.2 一致，根据手机号查询用户是否在数据库存在
        User user = query().eq("phone", phone).one();

        if(user==null){
            //2.2.1 用户不存在，创建新用户，保存进数据库
            user = createUserWithPhone(phone);
        }

        //2.2.2 用户存在或者新用户已创建，保存用户信息到session中
        //保存用户信息时，创建userDTO对象保存，防止敏感信息传送至前端
        /*
        UserDTO userDTO = new UserDTO();
        userDTO.setId(user.getId());
        userDTO.setNickName(user.getNickName());
        session.setAttribute("user", userDTO);
        */
        //修改为保存用户信息到redis中, 用户信息key为生成随机的token, User对象用hash存储为value
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);

        String token = UUID.randomUUID().toString(true);
        //session.setAttribute("user", userDTO);
        Map<String, Object> userDTOMap = BeanUtil.beanToMap(userDTO, new HashMap<>(),
                CopyOptions.create()
                        .setIgnoreNullValue(true)
                        .setFieldValueEditor((fieldName, fieldValue)-> fieldValue.toString()));//Long转String

        String tokenKey = LOGIN_USER_KEY + token;//添加业务前缀LOGIN_USER_KEY “login:token”
        stringRedisTemplate.opsForHash().putAll(tokenKey, userDTOMap);
        //设置user数据有效期, 参考session默认过期时间为30分钟
        stringRedisTemplate.expire(tokenKey, LOGIN_USER_TTL, TimeUnit.MINUTES);

        return Result.ok(token);

    }

    private User createUserWithPhone(String phone){
        User user = new User();
        user.setPhone(phone);
        user.setNickName("新用户_"+RandomUtil.randomString(12));

        //Mybatis plus保存新用户
        save(user);

        return user;
    }

    /**
     * 签到信息写入redis
     */
    @Override
    public Result sign() {
        //1 获取用户
        Long userId = UserHolder.getUser().getId();
        //2 获取当前日期
        LocalDateTime time = LocalDateTime.now();
        String yyyyMM = time.format(DateTimeFormatter.ofPattern("yyyyMM"));

        //3 拼接key
        String key = "sign:" + userId.toString() + ":" + yyyyMM;

        //4 获取当日为本月第几天
        int dayOfMonth = time.getDayOfMonth();

        //5 写入redis SetBit key offset 1
        //参数只有 offset (第几天)
        stringRedisTemplate.opsForValue().setBit(key, dayOfMonth-1, true);

        return Result.ok();
    }

    /**
     * 计算连续签到天数
     */
    @Override
    public Result signCount() {
        //1 获取用户
        Long userId = UserHolder.getUser().getId();
        //2 获取当前日期
        LocalDateTime time = LocalDateTime.now();
        String yyyyMM = time.format(DateTimeFormatter.ofPattern("yyyyMM"));

        //3 拼接key
        String key = "sign:" + userId.toString() + ":" + yyyyMM;

        //4 获取当日为本月第几天
        int dayOfMonth = time.getDayOfMonth();

        //5 获取本月1号到今日的bit串
        List<Long> result = stringRedisTemplate.opsForValue().bitField(
                key,
                BitFieldSubCommands.create()
                        .get(BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth))
                        .valueAt(0)
        );

        if(result==null || result.isEmpty()){
            return Result.ok(0);
        }

        Long bit = result.get(0);

        if(bit==null||bit==0){
            return Result.ok(0);
        }

        //6 循环遍历最后一位是否为1，为1计数器+1，为0结束
        int count=0;

        while ((bit & 1) != 0) {
            count++;
            bit = bit >> 1;
        }

        return Result.ok(count);
    }

}
